/***********************
 * 项目管理页面逻辑代码
 ***********************/
$(function () {
    function project() {
        let _extentMap, _extentLayer;
        let _pageSize = 10, _currentPage = 1;
        let _projects = [], _currentProject;
        let _isEdit = false;
        //let _extentMap,_extentLayer;
        let initLatlng = [30.595188, 114.299625];

        /**
         * 初始化
         */
        function init() {
            loadData();
        }

        /**
         * 初始化UI事件
         */
        function initUI() {
            $('#btn_project_search').on('click', function () {
                loadData();
            });

            $('#btn_project_add').on('click', function () {
                _isEdit = false;
                $('#modal_project_edit').modal('show')
            });

            $('#btn_project_save').on('click', function () {
                if (_isEdit) {
                    _currentProject.name = $('#input_project_name').val();
                    _currentProject.minLongitude = $('#input_project_minlon').val();
                    _currentProject.maxLongitude = $('#input_project_maxlon').val();
                    _currentProject.minLatitude = $('#input_project_minlat').val();
                    _currentProject.maxLatitude = $('#input_project_maxlat').val();

                    $.ajax({
                        url: `${Config.BASE_URL}/api/project`,
                        type: 'PUT',
                        data: JSON.stringify(_currentProject),
                        success: response => {
                            if (response.succeeded) {
                                $.notify('修改成功！', { type: 'success' });
                                $('#modal_project_edit').modal('hide');
                                loadData();
                            }
                            else {
                                $.notifyErrors(response.errors);
                            }
                        }
                    });
                }
                else {
                    var data = {
                        name: $('#input_project_name').val(),
                        minLongitude: $('#input_project_minlon').val(),
                        maxLongitude: $('#input_project_maxlon').val(),
                        minLatitude: $('#input_project_minlat').val(),
                        maxLatitude: $('#input_project_maxlat').val()
                    }

                    $.post(`${Config.BASE_URL}/api/project`, JSON.stringify(data), function (response) {
                        if (response.succeeded) {
                            $.notify('添加成功！', { type: 'success' });
                            $('#modal_project_edit').modal('hide');
                            loadData();
                        }
                        else {
                            $.notifyErrors(response.errors);
                        }
                    })
                }
            });

            _extentMap = L.map('extent_map').setView(initLatlng, 17);
            const tdtOption = {
                key: '304bc664f193742e0ad7ad3b77d5dccd'
            }

            L.tileLayer.chinaProvider('TianDiTu.Normal.Map', tdtOption).addTo(_extentMap);
            L.tileLayer.chinaProvider('TianDiTu.Normal.Annotion', tdtOption).addTo(_extentMap);

            //范围编辑相关的内容
            _extentMap.pm.setLang('zh');

            _extentMap.pm.addControls({
                position: 'topleft',
                drawControls: false,
                editControls: false,
                customControls: true
            });

            _extentMap.pm.Toolbar.copyDrawControl('Rectangle', {
                name: 'Rectangle_Copy',
                block: 'custom',
                title: '绘制范围'
            });

            _extentMap.on('pm:drawstart', function (e) {
                if (_extentLayer) {
                    _extentMap.removeLayer(_extentLayer);
                }
            });

            _extentMap.on('pm:create', function (e) {
                _extentLayer = e.layer;
                $('#input_project_minlon').val(_extentLayer.getBounds().getWest());
                $('#input_project_minlat').val(_extentLayer.getBounds().getSouth());
                $('#input_project_maxlon').val(_extentLayer.getBounds().getEast());
                $('#input_project_maxlat').val(_extentLayer.getBounds().getNorth());
            });

            _extentMap.on('pm:drawend', function (e) {
                if (!_extentMap.hasLayer(_extentLayer) && _extentLayer) {
                    _extentMap.addLayer(_extentLayer)
                }
            });


            //编辑窗口展示事件
            $('#modal_project_edit').on('shown.bs.modal', function (event) {
                if (_extentLayer) {
                    _extentMap.removeLayer(_extentLayer);
                }
                _extentMap.invalidateSize();
                if (_isEdit) {
                    $('#input_project_name').val(_currentProject.name);
                    var bounds = [[_currentProject.minLatitude, _currentProject.minLongitude], [_currentProject.maxLatitude, _currentProject.maxLongitude]];
                    $('#input_project_minlon').val(_currentProject.minLongitude);
                    $('#input_project_minlat').val(_currentProject.minLatitude);
                    $('#input_project_maxlon').val(_currentProject.maxLongitude);
                    $('#input_project_maxlat').val(_currentProject.maxLatitude);
                    _extentLayer = L.rectangle(bounds).addTo(_extentMap);
                    _extentMap.fitBounds(bounds);
                }
                else {
                    $('#input_project_name').val('');
                    var bounds = [[initLatlng[0] - 0.001, initLatlng[1] - 0.0015], [initLatlng[0] + 0.001, initLatlng[1] + 0.0015]];
                    $('#input_project_minlon').val(initLatlng[1] - 0.0015);
                    $('#input_project_minlat').val(initLatlng[0] - 0.001);
                    $('#input_project_maxlon').val(initLatlng[1] + 0.0015);
                    $('#input_project_maxlat').val(initLatlng[0] + 0.001);
                    _extentLayer = L.rectangle(bounds).addTo(_extentMap);
                    _extentMap.fitBounds(bounds);
                }
                L.PM.reInitLayer(_extentLayer);
            })
        }

        /**
         * 加载数据
         * @param {*} page 
         */
        function loadData(page = 1) {
            _currentPage = page;
            $('#project_table tbody').empty();
            let data = {
                keyword: $('#input_project_search').val(),
                page: page,
                size: _pageSize
            };

            $.post(`${Config.BASE_URL}/api/project/list`, JSON.stringify(data), function (response) {
                if (response.succeeded) {
                    _projects = response.data.items;
                    _projects.forEach(project => {
                        $('#project_table tbody').append(
                            `
                            <tr>
                                <th scope="row">${project.id}</th>
                                <td>${project.name}</td>
                                <td>${project.minLongitude},${project.minLatitude},${project.maxLongitude},${project.maxLatitude},</td>
                                <td>
                                    <span>
                                        <a class="tb-option option-edit">编辑</a>
                                        <div role="separator" class="divider divider-vertical"></div>
                                        <a class="tb-option option-delete">删除</a>
                                    </span>
                                </td>
                            </tr>
                            `
                        );
                    });

                    setOptions();
                    showPagination(response.data);
                }
            });

        }

        /**
         * 设置表格操作按钮事件
         */
        function setOptions() {
            $('#project_table .option-edit').on('click', function () {
                var tr = $(this).parent().parent().parent();
                _currentProject = _projects[tr.index()];
                _isEdit = true;
                $('#modal_project_edit').modal('show')
            });

            $('#project_table .option-delete').on('click', function () {
                if (confirm('删除后将不可恢复，是否删除')) {
                    var tr = $(this).parent().parent().parent();
                    var project = _projects[tr.index()];
                    $.ajax({
                        url: `${Config.BASE_URL}/api/project/${project.id}`,
                        type: 'DELETE',
                        data: JSON.stringify(_currentProject),
                        success: response => {
                            if (response.succeeded) {
                                $.notify('删除成功！', { type: 'success' });
                                loadData();
                            }
                            else {
                                $.notifyErrors(response.errors);
                            }
                        }
                    })
                }

            });
        }

        /***
         * 展示分页组件
         */
        function showPagination(pageData) {
            $('#project_pagination').empty();
            var preBtn = $(`<li class="page-item ${pageData.hasPrevPages ? '' : 'disabled'}">${pageData.hasPrevPages ? '<a class="page-link" href="#">上一页</a>' : '<span class="page-link">上一页</span>'}</li>`);
            pageData.hasPrevPages && preBtn.on('click', function () {
                if (pageData.pageIndex > 1) {
                    loadDatas(pageData.pageIndex - 1);
                }
            })
            $('#project_pagination').append(preBtn);
            for (let i = 0; i < pageData.totalPages; i++) {
                var pageBtn = $(`<li class="page-item ${pageData.pageIndex == (i + 1) ? 'active' : ''}">${pageData.pageIndex == (i + 1) ? '<span class="page-link">' + (i + 1) + '</span>' : '<a class="page-link" href="#">' + (i + 1) + '</a>'}</li>`);
                pageData.pageIndex != (i + 1) && pageBtn.on('click', function () {
                    loadDatas(i + 1);
                });
                $('#project_pagination').append(pageBtn);
            }
            var nextBtn = $(`<li class="page-item ${pageData.hasNextPages ? '' : 'disabled'}">${pageData.hasNextPages ? '<a class="page-link" href="#">下一页</a>' : '<span class="page-link">下一页</span>'}</li>`);
            pageData.hasNextPages && nextBtn.on('click', function () {
                if (pageData.pageIndex < pageData.totalPages) {
                    loadDatas(pageData.pageIndex + 1);
                }
            })
            $('#project_pagination').append(nextBtn);
        }

        return {
            init: init,
            initUI: initUI
        }
    }

    window.Project = project();
    Project.initUI();
})